import { createFileRoute } from '@tanstack/react-router'
import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { StorageService } from '../services/storage'
import { EditableText } from '../components/EditableText'
import { TimelineEventForm } from '../components/TimelineEventForm'

interface StoryData {
  meetingStory: {
    his: string
    hers: string
  }
  heartMoment: string
  timeline: Array<{
    id: number
    date: string
    title: string
    content: string
  }>
}

function OurStory() {
  const [storyData, setStoryData] = useState<StoryData>({
    meetingStory: { his: '', hers: '' },
    heartMoment: '',
    timeline: []
  })
  const [editMode, setEditMode] = useState<string | null>(null)
  const [showAddTimeline, setShowAddTimeline] = useState(false)

  // 加载数据
  useEffect(() => {
    const savedStory = StorageService.getOurStory()
    if (savedStory.timeline.length > 0 || savedStory.meetingStory.his || savedStory.meetingStory.hers) {
      setStoryData(savedStory)
    } else {
      // 默认数据
      const defaultStory: StoryData = {
        meetingStory: {
          his: '那是一个阳光明媚的下午，我第一次见到她时，时间仿佛静止了。她穿着一件白色的连衣裙，微风轻抚着她的长发，那一刻我知道，我遇到了生命中最重要的人。',
          hers: '记得那天我穿了一件白色的裙子，有些紧张地走进咖啡厅。当我看到他温暖的笑容时，所有的紧张都消失了，心中涌起一种前所未有的安全感。'
        },
        heartMoment: '就是那一刻，当我们四目相对时，我知道就是她了。不需要言语，不需要解释，心跳声告诉了我一切。从那一刻起，我的世界有了新的意义。',
        timeline: [
          {
            id: 1,
            date: '2024.01.15',
            title: '第一次约会',
            content: '我们去了那家小咖啡店，聊了整整一个下午，从书籍到梦想，从过去到未来，仿佛有说不完的话题。'
          },
          {
            id: 2,
            date: '2024.02.14',
            title: '第一次旅行',
            content: '我们一起去了海边，看日出日落，在沙滩上留下足迹，那是我们第一次真正意义上的旅行。'
          },
          {
            id: 3,
            date: '2024.03.20',
            title: '告白日',
            content: '那天晚上，在星空下，我们互相表达了心意。那一刻的美好，至今还深深印在我的心里。'
          }
        ]
      }
      setStoryData(defaultStory)
      StorageService.saveOurStory(defaultStory)
    }
  }, [])

  // 保存数据
  const saveStoryData = (newData: StoryData) => {
    setStoryData(newData)
    StorageService.saveOurStory(newData)
  }

  // 更新相遇故事
  const updateMeetingStory = (type: 'his' | 'hers', content: string) => {
    const newData = {
      ...storyData,
      meetingStory: {
        ...storyData.meetingStory,
        [type]: content
      }
    }
    saveStoryData(newData)
    setEditMode(null)
  }

  // 更新心动瞬间
  const updateHeartMoment = (content: string) => {
    const newData = {
      ...storyData,
      heartMoment: content
    }
    saveStoryData(newData)
    setEditMode(null)
  }

  // 添加时间线事件
  const addTimelineEvent = (event: Omit<StoryData['timeline'][0], 'id'>) => {
    const newEvent = {
      ...event,
      id: Date.now()
    }
    const newData = {
      ...storyData,
      timeline: [...storyData.timeline, newEvent]
    }
    saveStoryData(newData)
    setShowAddTimeline(false)
  }

  // 删除时间线事件
  const deleteTimelineEvent = (id: number) => {
    if (confirm('确定要删除这个事件吗？')) {
      const newData = {
        ...storyData,
        timeline: storyData.timeline.filter(event => event.id !== id)
      }
      saveStoryData(newData)
    }
  }
  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-50 to-orange-50">
      <div className="container mx-auto px-4 py-8">
        <h1 className="text-4xl font-bold text-center text-gray-800 mb-8 font-serif">
          我们的故事 💕
        </h1>
        
        <div className="max-w-4xl mx-auto space-y-12">
          {/* 相遇篇 */}
          <section className="bg-white/80 backdrop-blur-sm rounded-2xl p-8 shadow-lg">
            <h2 className="text-2xl font-semibold text-pink-600 mb-6 flex items-center">
              <span className="mr-3">🌸</span>
              相遇篇
            </h2>
            <div className="grid md:grid-cols-2 gap-8">
              <div className="space-y-4">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-lg font-medium text-gray-700">他的视角</h3>
                  <button
                    onClick={() => setEditMode('his')}
                    className="text-blue-500 hover:text-blue-700 text-sm"
                  >
                    ✏️ 编辑
                  </button>
                </div>
                {editMode === 'his' ? (
                  <EditableText
                    initialValue={storyData.meetingStory.his}
                    onSave={(content) => updateMeetingStory('his', content)}
                    onCancel={() => setEditMode(null)}
                    placeholder="写下你第一次见到她时的心情和感受..."
                  />
                ) : (
                  <p className="text-gray-600 leading-relaxed">
                    {storyData.meetingStory.his || '点击编辑按钮，写下你的第一印象和当时的心情'}
                  </p>
                )}
              </div>
              <div className="space-y-4">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="text-lg font-medium text-gray-700">她的视角</h3>
                  <button
                    onClick={() => setEditMode('hers')}
                    className="text-blue-500 hover:text-blue-700 text-sm"
                  >
                    ✏️ 编辑
                  </button>
                </div>
                {editMode === 'hers' ? (
                  <EditableText
                    initialValue={storyData.meetingStory.hers}
                    onSave={(content) => updateMeetingStory('hers', content)}
                    onCancel={() => setEditMode(null)}
                    placeholder="写下你第一次见到他时的心情和感受..."
                  />
                ) : (
                  <p className="text-gray-600 leading-relaxed">
                    {storyData.meetingStory.hers || '点击编辑按钮，写下她的第一印象和当时的心情'}
                  </p>
                )}
              </div>
            </div>
          </section>

          {/* 心动瞬间 */}
          <section className="bg-white/80 backdrop-blur-sm rounded-2xl p-8 shadow-lg">
            <h2 className="text-2xl font-semibold text-pink-600 mb-6 flex items-center">
              <span className="mr-3">💖</span>
              心动瞬间
            </h2>
            <div className="space-y-6">
              <div className="border-l-4 border-pink-300 pl-6">
                <h3 className="text-lg font-medium text-gray-700 mb-2">那个确定的时刻</h3>
                <div className="flex items-center justify-between mb-4">
                  <div></div>
                  <button
                    onClick={() => setEditMode('heart')}
                    className="text-blue-500 hover:text-blue-700 text-sm"
                  >
                    ✏️ 编辑
                  </button>
                </div>
                {editMode === 'heart' ? (
                  <EditableText
                    initialValue={storyData.heartMoment}
                    onSave={(content) => updateHeartMoment(content)}
                    onCancel={() => setEditMode(null)}
                    placeholder="写下让你们心动的那个特殊瞬间..."
                  />
                ) : (
                  <p className="text-gray-600 leading-relaxed">
                    {storyData.heartMoment || '点击编辑按钮，写下让你们心动的那个特殊瞬间'}
                  </p>
                )}
              </div>
            </div>
          </section>

          {/* 大事记 */}
          <section className="bg-white/80 backdrop-blur-sm rounded-2xl p-8 shadow-lg">
            <h2 className="text-2xl font-semibold text-pink-600 mb-6 flex items-center">
              <span className="mr-3">📅</span>
              爱情大事记
            </h2>
            <div className="flex justify-between items-center mb-6">
              <div></div>
              <button
                onClick={() => setShowAddTimeline(true)}
                className="px-4 py-2 bg-pink-500 text-white rounded-lg hover:bg-pink-600 transition-colors"
              >
                ➕ 添加事件
              </button>
            </div>
            
            <div className="space-y-6">
              {storyData.timeline.map((event) => (
                <motion.div
                  key={event.id}
                  className="timeline-item flex items-start space-x-4 group"
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                >
                  <div className="w-4 h-4 bg-pink-400 rounded-full mt-2 flex-shrink-0"></div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-medium text-gray-700">
                        {event.date} - {event.title}
                      </h3>
                      <button
                        onClick={() => deleteTimelineEvent(event.id)}
                        className="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700 transition-opacity"
                      >
                        🗑️
                      </button>
                    </div>
                    <p className="text-gray-600 mt-1">{event.content}</p>
                  </div>
                </motion.div>
              ))}
              
              {storyData.timeline.length === 0 && (
                <div className="text-center py-8 text-gray-500">
                  还没有添加任何事件，点击上方按钮开始记录你们的爱情大事记 💕
                </div>
              )}
            </div>
            
            <TimelineEventForm
              isOpen={showAddTimeline}
              onClose={() => setShowAddTimeline(false)}
              onSubmit={addTimelineEvent}
            />
          </section>
        </div>
      </div>
    </div>
  )
}

export const Route = createFileRoute('/our-story')({
  component: OurStory,
})
